package com.llap.exp190929.controller;

import com.llap.exp190929.dto.CredentialDto;
import com.llap.exp190929.dto.PaginatedDto;
import com.llap.exp190929.entity.CardAccount;
import com.llap.exp190929.error.RestException;
import com.llap.exp190929.service.CardAccountService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * Created by LLAP on 2019/10/14.
 * Copyright (c) 2019 LLAP. All rights reserved.
 */
@RestController
@RequestMapping("cards")
@AllArgsConstructor
@CrossOrigin
@Slf4j
public class CardAccountsController {
    private CardAccountService cardaccountService;

    @GetMapping("")
    public PaginatedDto<CardAccount> findCardAccounts(
            @RequestParam(required = false, defaultValue = "1") Integer page,
            @RequestParam(required = false, defaultValue = "20") Integer pageSize) {
        return PaginatedDto.from(cardaccountService.findCardAccounts(page, pageSize));
    }

    @PostMapping("authenticate")
    public CardAccount authCardAccount(@RequestBody CredentialDto credential) throws RestException {
        return cardaccountService.findCardAccount(credential.getUsername(), credential.getPassword());
    }

    @GetMapping("{id}")
    public CardAccount findCardAccount(@PathVariable String id) {
        CardAccount ret = cardaccountService.findCardAccount(id);
        if (ret != null) ret.eraseCredential();
        return ret;
    }

    @PostMapping("")
    public CardAccount addCardAccount(@RequestBody CardAccount cardAccount) {
        return cardaccountService.addCardAccount(cardAccount);
    }

    @DeleteMapping("")
    public void deleteCardAccount(@RequestParam String id) {
        cardaccountService.deleteCardAccount(id);
    }

    @PatchMapping("")
    public CardAccount updateCardAccount(@RequestBody CardAccount cardAccount) {
        return cardaccountService.updateCardAccount(cardAccount);
    }
}
